<template>
   <!-- 添加和编辑次级组织 -->
   <div class="addMask">
      <el-dialog
         v-model="open"
         :title="title"
         width="40%"
      >
         <el-form
            :model="formData"
            ref="formDataRef"
            label-width="100px"
            :rules="rules"
         >
            <el-form-item
               label="上级组织："
               prop="parent_id"
            >
               <el-select
                  v-model="formData.parent_id"
                  placeholder="选择上级组织"
                  style="width: 400px"
                  @change="onClick"
                  clearable
                  :disabled="!notClickable"
               >
                  <el-option
                     v-for="item in orgList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"
                  />
               </el-select>
            </el-form-item>
            <el-form-item
               label="组织名称："
               prop="name"
            >
               <el-input
                  v-model="formData.name"
                  placeholder="请输入组织名称"
                  style="width: 400px"
               />
            </el-form-item>
            <el-form-item
               label="组织编号："
               prop="num"
            >
               <el-input
                  v-model="formData.num"
                  placeholder="格式为ORG+4位随机数"
                  style="width: 400px"
               />
               <el-button
                  type="success"
                  style="margin-left: 10px"
                  @click="generateWorkNo"
                  >分配组织编号</el-button
               >
            </el-form-item>
            <el-form-item
               label="组织主管："
               prop="manager_id"
               v-if="notClickable"
            >
               <el-select
                  v-model="formData.manager_id"
                  placeholder="选择组织主管"
                  filterable
                  style="width: 400px"
                  clearable
                  @clear="() => (formData.manager_id = 0)"
               >
                  <el-option
                     v-for="item in managerList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"
                  />
               </el-select>
            </el-form-item>
            <el-form-item
               label="组织类型："
               prop="type"
            >
               <el-radio-group v-model="formData.type">
                  <el-radio :label="1">部门</el-radio>
                  <el-radio :label="2">公司</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item
               label="状态："
               prop="status"
            >
               <el-radio-group v-model="formData.status">
                  <el-radio
                     v-for="item in statusType"
                     :key="item.value"
                     :label="item.value"
                  >
                     {{ item.label }}
                  </el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item
               label="描述说明："
               prop="content"
            >
               <el-input
                  type="textarea"
                  v-model="formData.content"
                  placeholder="请输入描述说明"
                  :autosize="{ minRows: 5 }"
                  style="width: 400px"
               />
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button
                  type="success"
                  @click="submitDialog"
                  >立即提交</el-button
               >
               <el-button @click="open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup>
   import api from "@/api/index.js";
   import { ElMessage } from "element-plus";
   import { ref, reactive, computed, onMounted, defineExpose } from "vue";
   const emit = defineEmits(["init"]);
   const open = ref(false);
   const formRef = ref(null);

   // 表单数据初始化
   const formData = ref({
      id: null,
      name: "",
      parentId: "",
      type: 1, // 默认部门类型
      status: "",
      content: "",
      num: "",
      manager_id: "",
      status: "", // 状态0禁用1启用
   });
   // 组织类型
   const statusType = ref([
      { label: "禁用", value: 0 },
      { label: "启用", value: 1 },
   ]);
   // 组织列表数据
   let orgList = ref([]);
   // 管理人员列表
   let managerList = ref([]);
   // 生成组织编号  
   const generateWorkNo = async () => {
      // 这里可以调用接口生成工号，或使用前端生成的临时工号
      const res = await api.authority.getRanNum({ type: "org" });
      if (res.code == 200) {
         formData.value.num = String(res.data); // 确保转换为字符串
      }
   };
   // 递归处理数据
   const recursive = (data) => {
      if (!data || !Array.isArray(data)) return [];

      data.forEach((item) => {
         if (item) {
            orgList.value.push({
               id: item.id,
               name: item.name,
            });
            if (item.children && item.children.length > 0) {
               recursive(item.children);
            }
         }
      });
   };
   // 获取组织列表
   const getOrgList = async () => {
      try {
         const res = await api.authority.getOrgList();
         if (res.code === 200) {
            orgList.value = []; // 先清空数组
            recursive(res.data); // 递归处理数据
         } else {
            ElMessage.error(res.msg || "获取组织列表失败");
         }
      } catch (error) {
         console.error("获取组织列表失败:", error);
         ElMessage.error("获取组织列表失败，请稍后再试");
      }
   };
   const onClick = async (value) => {
      await getManagerList(value);
   };
   // 获取管理人员列表
   const getManagerList = async (value) => {
      if (!value) {
         managerList.value = [];
         return;
      }

      try {
         const res = await api.authority.getPersonnelList({
            // org_id: value,
            // job_status: 1, // 只获取在职人员
         });

         if (res.code === 200) {
            if (Array.isArray(res.data)) {
               managerList.value = res.data;
            } else if (res.data && Array.isArray(res.data.data)) {
               managerList.value = res.data.data;
               managerList.value.push({
                  id: 0,
                  name: "无上级主管",
               });
            } else {
               managerList.value = [];
            }
         } else {
            ElMessage.error(res.msg || "获取管理人员失败");
            managerList.value = [];
         }
      } catch (error) {
         console.error("获取管理人员失败:", error);
         ElMessage.error("获取管理人员失败，请稍后再试");
         managerList.value = [];
      }
   };

   //
   const notClickable = ref(false);
   // 打开弹窗方法
   const handleDialog = async (item, type) => {
      console.log(item);
      // 打开弹窗前先获取组织列表
      await getOrgList();

      if (type === "add") {
         notClickable.value = false;
         // 检查 item 是否存在再进行赋值，避免 null 引用错误
         if (item) {
            formData.value.parent_id = item.id;
            console.log(formData.value.parent_id);
         }

         // 新增时重置表单
         formData.value = {
            id: null,
            name: "",
            parent_id: item ? item.id : "",
            type: "",
            status: "",
            content: "",
            num: "",
            manager_id: "",
         };

         // 如果有父级ID，加载管理人员列表
         if (formData.value.parent_id) {
            await getManagerList(formData.value.parent_id);
         }
      } else if (type === "edit") {
         notClickable.value = true;
         try {
            // 获取组织详情
            let res = await api.authority.getOrgDetail({ id: item.id });

            if (res.code === 200 && res.data) {
               // 如果有上级组织，获取该组织的管理人员列表
               if (res.data.parent_id) {
                  await getManagerList(res.data.parent_id);
               }

               // 编辑时的数据处理
               formData.value = {
                  id: res.data.id,
                  parent_id: res.data.parent_id || "",
                  parent_name: res.data.parent_name || "",
                  name: res.data.name,
                  num: res.data.num || "",
                  type: res.data.type || 1,
                  type_name: res.data.type_name || "",
                  manager_id: res.data.manager_id || "",
                  content: res.data.content || "",
                  status: res.data.status === undefined ? 1 : Number(res.data.status), // 确保status是数字类型
               };
            } else {
               ElMessage.error(res.msg || "获取组织详情失败");
            }
         } catch (error) {
            console.error("获取组织详情失败:", error);
            ElMessage.error("获取组织详情失败，请稍后再试");
         }
      }
      open.value = true;
   };

   // 计算属性
   const title = computed(() => {
      return formData.value.id ? "编辑组织" : "新增组织";
   });

   // 定义验证规则
   const rules = reactive({
      name: [
         { required: true, message: "请输入组织名称", trigger: "blur" },
         { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
      ],
      num: [
         { required: true, message: "请输入组织编号", trigger: "blur" },
         { type: 'string', message: "组织编号必须是字符串", trigger: "blur" },
         { pattern: /^[A-Za-z0-9]+$/, message: "只能输入字母和数字", trigger: "blur" },
      ],
      type: [{ required: true, message: "请选择组织类型", trigger: "change" }],
      content: [
         { required: false }, // 可选字段，可以根据需求修改
         { max: 200, message: "描述不能超过200个字符", trigger: "blur" },
      ],
   });

   const formDataRef = ref(null);

   // 提交表单
   const submitDialog = () => {
      formDataRef.value.validate(async (valid) => {
         if (valid) {
            try {
               // 根据是否有ID判断是编辑还是新增
               const apiMethod = formData.value.id
                  ? api.authority.editOrganization // 编辑
                  : api.authority.addOrganization; // 新增组织

               // 默认上级组织为0（顶级组织）
               formData.value.parent_id = formData.value.parent_id || 0;

               // 确保组织编号是字符串类型
               const submitData = {
                  ...formData.value,
                  num: String(formData.value.num)
               };

               // 过滤掉空值字段
               const filteredFormData = Object.fromEntries(
                  Object.entries(submitData).filter(([_, value]) => value !== "" && value !== null && value !== undefined)
               );

               const res = await apiMethod(filteredFormData);
               if (res.code === 200) {
                  ElMessage.success(formData.value.id ? "编辑成功" : "添加成功");
                  open.value = false;
                  emit("init"); // 通知父组件刷新数据
               } else {
                  ElMessage.error(res.msg || (formData.value.id ? "编辑失败" : "添加失败"));
               }
            } catch (error) {
               console.error("提交失败:", error);
               ElMessage.error("操作失败，请稍后再试");
            }
         } else {
            ElMessage.warning("请完善表单信息");
         }
      });
   };

   defineExpose({
      handleDialog,
   });

   onMounted(() => {
      // 组件挂载时不需要立即加载数据，在打开弹窗时才加载
   });
</script>

<style lang="scss" scoped>
   .dialog-footer {
      display: flex;
      justify-content: center;
      margin-top: 20px;
   }
</style>
